<script setup lang="ts">
import {
    Search,
    Plus,
    MuteNotification,
    Back,
    Right,
    RefreshRight,
    House,
    Link
} from '@element-plus/icons-vue'
import ChatMenuEdit from './ChatMenuEdit.vue'
import { ref, reactive, shallowRef, nextTick, watch } from 'vue'
import { deepClone } from '../../utils/json'
import dayjs from 'dayjs'
import toObject from 'dayjs/plugin/toObject'

dayjs.extend(toObject)

const editRef = shallowRef()
const showEdit = ref(false)

const emit = defineEmits(['active'])

const props = defineProps({
    menus: {
        type: Array<ChatMenu>,
        default: () => []
    },
    host: {
        type: String,
        default: 'https://unshell.github.io/expand/ads.html'
    },
    activeId: {
        type: String,
        default: ''
    },
    webviewHome: {
        type: String,
        default: 'https://www.bing.com'
    }
})

const activeId = ref('')

watch(() => props.activeId, (now, _) => {
    activeId.value = now
})

const website = reactive({
    element: null as HTMLWebViewElement | null,
    src: '',
    effective: false,
    back: false,
    forward: false,
    videos: [
        {
            title: '哔哩哔哩',
            url: 'https://www.bilibili.com/'
        },
        {
            title: '腾讯视频',
            url: 'https://v.qq.com/'
        },
        {
            title: '爱奇艺视频',
            url: 'https://www.iqiyi.com/'
        },
        {
            title: '优酷视频',
            url: 'https://www.youku.com/'
        },
        {
            title: '芒果TV',
            url: 'https://www.mgtv.com/'
        },
        {
            title: '抖音 - 推荐',
            url: 'https://www.douyin.com/?recommend=1'
        }
    ],
})

const handleOpenDropdown = () => {
    const webview = document.querySelector('webview') as HTMLWebViewElement
    website.element = webview
    if (webview) {
        website.effective = true
        website.back = webview.canGoBack()
        website.forward = webview.canGoForward()
    } else {
        website.effective = false
        website.back = false
        website.forward = false
    }
}

const handleWebsite = (type: string) => {
    switch (type) {
        case 'back':
            website.element?.goBack()
            break
        case 'right':
            website.element?.goForward()
            break
        case 'refresh':
            website.element?.reload()
            break
        case 'home':
            website.element?.loadURL(props.webviewHome)
            break
    }
}

const showMenuEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open(data)
}

const handleEditConfirm = (data: ChatMenu) => {
    if (!data.id) {
        data.id = window.electronIpc.randomUUID()
        props.menus.push(data)
    } else {
        const index = props.menus.findIndex(menu => menu.id === data.id)
        props.menus[index] = data
    }
    let clone = deepClone(props.menus)
    window.ipcRenderer.send('set-config', { wechat: { menus: clone } })
}

const handleSearch = () => {
    handleOpenDropdown()

    if (website.effective && website.element) {
        if (website.src.startsWith('http://') || website.src.startsWith('https://')) {
            website.element.src = website.src
        } else {
            website.element.src = `https://www.bing.com/search?q=${website.src}`
        }
        website.element.focus()
        website.src = ''
    }
}

const handleActive = (data: ChatMenu) => {
    if (activeId.value === data.id) {
        activeId.value = ''
        emit('active', undefined)
    } else {
        activeId.value = data.id
        data.isRead = true
        emit('active', data.type === 0 ? data : undefined)
    }
}

const handleIsTop = (data: ChatMenu) => {
    const index = props.menus.findIndex(menu => menu.id === data.id)
    data.isTop = !data.isTop
    if (data.isTop) {
        props.menus.splice(index, 1)
        props.menus.unshift(data)
    } else {
        props.menus.splice(index, 1)
        const noTopIndex = props.menus.findIndex(menu => !menu.isTop)
        props.menus.splice(noTopIndex, 0, data)
    }
}

const handleDelete = (data: ChatMenu) => {
    const index = props.menus.findIndex(menu => menu.id === data.id)
    props.menus.splice(index, 1)
    window.ipcRenderer.send('set-config', { wechat: { menus: deepClone(props.menus) } })
}

const handleTime = (time: string) => {
    if (!dayjs().isSame(time, 'year')) {
        return dayjs(time).format('YYYY/MM/DD')
    }
    if (!dayjs().isSame(time, 'day')) {
        if (dayjs().diff(time, 'hour') < 48) {
            return '昨天 ' + dayjs(time).format('HH:mm')
        }
        return dayjs(time).format('MM/DD')
    }
    return dayjs(time).format('HH:mm')
}
</script>
<template>
    <div class="chat-menu no-drag">
        <div class="search">
            <el-input v-model="website.src" placeholder="搜索" @keyup.enter="handleSearch" :prefix-icon="Search" />
            <el-button text title="操作">
                <template #icon>
                    <el-dropdown popper-class="wechat-dropdown" @visible-change="handleOpenDropdown" trigger="click">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="showMenuEdit">
                                    新增聊天
                                </el-dropdown-item>
                                <el-dropdown-item :icon="Back" :disabled="!website.effective || !website.back" divided
                                    @click="handleWebsite('back')">
                                    上一页
                                </el-dropdown-item>
                                <el-dropdown-item :icon="Right" :disabled="!website.effective || !website.forward"
                                    @click="handleWebsite('right')">
                                    下一页
                                </el-dropdown-item>
                                <el-dropdown-item :icon="RefreshRight" :disabled="!website.effective"
                                    @click="handleWebsite('refresh')">
                                    刷新
                                </el-dropdown-item>
                                <el-dropdown-item :icon="House" :disabled="!website.effective"
                                    @click="handleWebsite('home')">
                                    首页
                                </el-dropdown-item>
                                <el-dropdown-item :icon="Link" v-for="(video, index) in website.videos"
                                    :disabled="!website.effective" @click="website.element?.loadURL(video.url)"
                                    :divided="index === 0">
                                    {{ video.title }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-button>
        </div>
        <el-scrollbar class="chat-group">
            <template v-for="menu in props.menus">
                <div :class="{
                    'chat': true,
                    'is-top': menu.isTop,
                    'active': menu.id === activeId
                }" @click="handleActive(menu)">
                    <el-dropdown popper-class="wechat-dropdown" trigger="contextmenu">
                        <el-badge :hidden="menu.isRead" :is-dot="menu.type !== 0 || menu.isMute" :value="1">
                            <el-avatar shape="square" :size="100" :fit="menu.imageBlobUrl" :src="menu.imageBlobUrl" />
                        </el-badge>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="handleIsTop(menu)">
                                    {{ menu.isTop ? '取消置顶' : '置顶' }}
                                </el-dropdown-item>
                                <el-dropdown-item @click="menu.isRead = !menu.isRead">
                                    标为{{ menu.isRead ? '未' : '已' }}读
                                </el-dropdown-item>
                                <el-dropdown-item @click="menu.isMute = !menu.isMute">
                                    {{ menu.isMute ? '允许消息通知' : '消息免打扰' }}
                                </el-dropdown-item>
                                <el-dropdown-item divided @click="showMenuEdit(menu)">编辑</el-dropdown-item>
                                <el-dropdown-item @click="handleDelete(menu)">
                                    <el-text type="danger">删除</el-text>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <div class="info">
                        <p class="top">
                            <span class="name">{{ menu.title }}</span>
                            <span class="time">{{ handleTime(menu.time) }}</span>
                        </p>
                        <p class="bottom">
                            <span class="description">{{ menu.description }}</span>
                            <el-icon v-if="menu.isMute">
                                <MuteNotification />
                            </el-icon>
                        </p>
                    </div>
                </div>
            </template>
        </el-scrollbar>
    </div>
    <chat-menu-edit v-if="showEdit" :host="props.host" ref="editRef" @confirm="handleEditConfirm"
        @close="showEdit = false" />
</template>
<style lang="scss" scoped>
.chat-menu {
    background-color: #f7f7f7;
    border-left: 1px solid #d5d5d5;

    .search {
        display: flex;
        padding: 31px 10px 12px 10px;

        .el-input {
            height: 26px;
        }

        .el-button {
            height: 26px;
            padding-left: 6px;
            padding-right: 6px;
            margin-left: 8px;
            background-color: #eaeaea;

            &:hover {
                background-color: #e3e3e3;
            }
        }
    }

    .chat-group {
        height: calc(100vh - 85px);

        .chat {
            display: flex;
            padding: 15px 10px;
            cursor: default;

            :deep(.el-badge) {
                --el-badge-size: 16px;
                --el-badge-padding: 5px;

                .el-badge__content {
                    border: unset;
                }
            }

            &.is-top {
                background-color: #eaeaea;
            }

            &.active,
            &:hover {
                background-color: #dedede;
            }

            .el-avatar {
                flex-shrink: 0;
                width: 38px;
                height: 38px;
            }

            .info {
                width: 100%;
                display: flex;
                flex-wrap: wrap;
                max-height: 38px;
                padding-left: 10px;
                overflow: hidden;
                align-content: space-between;

                p {
                    width: 100%;
                    font-size: 14px;
                    line-height: 14px;

                    &.top {
                        display: flex;
                        align-items: flex-end;
                        justify-content: space-between;

                        span {
                            display: inline-block;
                            overflow: hidden;
                            white-space: nowrap;
                            text-overflow: ellipsis;

                            &.time {
                                font-size: 10px;
                                color: #8e8e8e;
                            }
                        }
                    }

                    &.bottom {
                        display: flex;
                        align-items: flex-end;
                        justify-content: space-between;
                        color: #8e8e8e;

                        .description {
                            display: inline-block;
                            overflow: hidden;
                            white-space: nowrap;
                            text-overflow: ellipsis;
                            font-size: 12px;
                        }

                        .el-icon {
                            margin-left: 3px;
                        }
                    }
                }
            }
        }
    }
}
</style>